﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraBars.Helpers;
using DevExpress.XtraBars.Docking2010.Views;
using System.Reflection;
using DevExpress.XtraSplashScreen;
using System.Configuration;
using CP.Utility;
using CP.Controllers.GPM;
using System.Linq;
using DevExpress.XtraNavBar;

namespace GPM
{
    public partial class FrmMain : DevExpress.XtraEditors.XtraForm
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.Text = AppSetter.SoftName;
            splashScreenManager1.ShowWaitForm();
            SkinHelper.InitSkinPopupMenu(barSkin);

            LoadNavBar();
            if (AppSetter.CurrentUser.user_id != "admin")
            {
                this.barInitialization.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                this.barMenuManage.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                this.barItemOptions.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            }
            ShowFirstPage();
            splashScreenManager1.CloseWaitForm();
        }

        private void LoadNavBar()
        {
            MenuController controller = new MenuController();
            IList<CP.Entities.Menu> menus = controller.GetMenusByUserID(AppSetter.CurrentUser.user_id);
            var parents = menus.Where(m => m.parent_id == 0);
            navBarMainMenu.BeginUpdate();
            navBarMainMenu.Groups.Clear();
            foreach (CP.Entities.Menu parent in parents)
            {
                NavBarGroup group = new NavBarGroup();
                group.Caption = parent.menu_name;
                group.SmallImageIndex = parent.image_index;
                group.LargeImageIndex = parent.image_index;

                navBarMainMenu.Groups.Add(group);

                var childs = menus.Where(m => m.parent_id == parent.menu_id);
                foreach (CP.Entities.Menu child in childs)
                {
                    string formName = "";
                    string nameSpace = "";
                    DataTable formDT = controller.GetFormInfoByMenuID(child.menu_id);
                    if (formDT.Rows.Count > 0)
                    {
                        formName = formDT.Rows[0]["form_name"] == DBNull.Value ? "" :
                                                formDT.Rows[0]["form_name"].ToString();
                        nameSpace = formDT.Rows[0]["name_space"] == DBNull.Value ? "" :
                                                formDT.Rows[0]["name_space"].ToString();
                    }

                    NavBarItem item = new NavBarItem();
                    item.Caption = child.menu_name;
                    item.Tag = formName + "," + nameSpace;
                    item.SmallImageIndex = child.image_index;
                    item.LargeImageIndex = child.image_index;

                    group.ItemLinks.Add(item);
                }
                group.Expanded = true;
            }
            
            navBarMainMenu.EndUpdate();
            navBarMainMenu.LinkClicked -= navBarMainMenu_LinkClicked;
            navBarMainMenu.LinkClicked += navBarMainMenu_LinkClicked;
        }

        private void navBarMainMenu_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            if (null == e.Link.Item.Tag)
            {
                ExMessageBox.Show("提示：该菜单没有绑定窗体！", AppSetter.SoftName);
                return;
            }
            try
            {
                splashScreenManager1.ShowWaitForm();
                string info = e.Link.Item.Tag.ToString();
                string formName = info.Substring(0, info.IndexOf(','));
                string nameSpace = info.Substring(info.IndexOf(',') + 1);
                ExtractForm(formName, nameSpace);
                splashScreenManager1.CloseWaitForm();
            }
            catch (System.IO.FileNotFoundException fex)
            {
                splashScreenManager1.CloseWaitForm();
                ExMessageBox.Show("提示：找不到菜单对应DLL文件！", AppSetter.SoftName);
            }
            catch (Exception ex)
            {
                splashScreenManager1.CloseWaitForm();
                ExMessageBox.Show("提示：该菜单没有绑定窗体！", AppSetter.SoftName);
            }

        }

        private void ExtractForm(string formName, string nameSpace)
        {
            foreach (BaseDocument document in tabbedView1.Documents)
            {
                if (document.Form.Name == formName)
                {
                    tabbedView1.Controller.Activate(document);
                    return;
                }
            }

            Assembly currentAssembly = Assembly.Load(nameSpace);
            Form xtraform = (Form)currentAssembly.CreateInstance(nameSpace + "." + formName);
            if (null != xtraform)
            {
                xtraform.MdiParent = this;
                xtraform.Show();
            }
        }

        private void btnReLogin_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
           
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Close();
        }

        private void barAbout_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmAbout about = new FrmAbout();
            about.ShowDialog();
        }

        private void barExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ExMessageBox.Confirm("提示信息：确定要退出吗？", AppSetter.SoftName) == DialogResult.No)
                return;
            this.Close();
        }

        private void barInitialization_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //ExtractForm("FrmWebpartDraw", "GPM");
            FrmWebpartDraw frm = new FrmWebpartDraw();
            frm.ShowDialog();
        }

        private void barMenuManage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ExtractForm("FrmMenu", "GPM");
        }

        private void barRefreshMenu_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            LoadNavBar();
            ExMessageBox.Show("提示消息：菜单刷新成功！",AppSetter.SoftName);
        }

        private void barSkin_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AppSetter.SetValue("Skin", DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName);
        }

        private void barItemOptions_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmUtility frmUtility = new FrmUtility();
            frmUtility.ShowDialog();
        }

        private void barItemChangePwd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FrmChangePassword frm = new FrmChangePassword();
            frm.ShowDialog();
        }

        private void barFirstPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowFirstPage();
        }

        private void ShowFirstPage()
        {
            foreach (BaseDocument document in tabbedView1.Documents)
            {
                if (document.Form.Name == "FrmFirstPage")
                {
                    tabbedView1.Controller.Activate(document);
                    return;
                }
            }

            FrmFirstPage firstPage = new FrmFirstPage();
            firstPage.MdiParent = this;
            firstPage.Show();
        }

        private void barReLogin_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AppSetter.SetValue("AutoLogin", "");
            FrmLogin login = new FrmLogin();
            login.ShowDialog();
        }
    }
}